<template>
<div>
    <!-- <Row>
        <Col span='12'>
        <div v-if="SearchPlanIsShow">
            <Input placeholder="请输入查询关键字" style="width: 200px" size="small"></Input>
            <Button type="primary" icon="ios-search" size="small">查询</Button>
        </div>
        </Col>
    </Row> -->
    <Row >
        <Col span="24">
        <Tag type="border" color="primary" v-for="item in queryArray" :key="item.key" closable @on-close="onCloseFilter(item)">{{item.name}}:{{item.val}}</Tag>

        </Col>
        <Col span='24'>
        <Table border stripe :columns="getColums" :data="tableData.data" @on-sort-change="onSortChange" @on-selection-change="onSelectionChange"></Table>
        </Col>
    </Row>
    <br>
    <Row  type="flex">
        <Col span='12'>
        <Button style="marginRight:5px" v-for="item in tableData.btnGroup" v-if="item.isShow" :icon="item.icon" :loading="item.loading" :key="item.text" :type="item.type" size="small" :disabled="btnGroupDisAbled" @click="onButtonClickEvent(item)">{{item.text}}</Button>
        <slot name="custom-button-group"></slot>
        </Col>
        <Col span='12'>
        <Row type="flex" justify="end" v-show="tableData.page.total>0">
            <Col>
            <Page :total="tableData.page.total" :current="tableData.page.current" :page-size="tableData.page.pageSize" size="small" show-elevator show-sizer :page-size-opts="[ 20, 30, 50,100]" @on-page-size-change="onPageSizeChange" @on-change="onChange"></Page>
            </Col>
        </Row>
        </Col>
    </Row>

</div>
</template>

<script>
import then from "thenjs";
import moment from "moment";
import AppFrame from "../libs/app-frame";
export default {
    props: ["border", "stripe", "rowKey", "columns", "data", "page", "btnGroup"],
    name: "manage-table",
    data: function () {
        return {
            tableData: {
                rowKey: this.rowKey,
                columns: this.columns,
                data: this.data,
                page: this.page,
                btnGroup: this.btnGroup
            },
            SearchPlanIsShow: true,
            btnGroupDisAbled: true,
            selectedRowKeys: [],
            query: {},
            queryArray: [],
            modal: {
                btnGroupModal: false,
                title: "提示",
                content: "",
                loading: false,
                clickOkBtn: function () {}
            }
        };
    },

    computed: {
        getColums: function () {
            return this.tableData.columns;
        }
    },

    watch: {
        $route: function () {
            //当路由改变时
            this.getQuery();
        },
        getColums: {
            handler: function (curVal, oldVal) {
                this.getQuery();
            },
            deep: true
        }
    },
    created: function () {
        let self = this;
        this.getQuery();
        let CurPageUserAble = AppFrame.UserModule.GetModuleByUrl(location.pathname);
        if (CurPageUserAble) {
            for (let i = this.tableData.columns.length - 1; i > -1; i--) {
                let able = this.tableData.columns[i].able;
                if(able && CurPageUserAble.Able.indexOf(able) > -1){
                    this.tableData.columns.splice(i,1);
                }
            }

            for(let i=this.tableData.btnGroup.length - 1;i>-1;i--){
                let able = this.tableData.btnGroup[i].able;
                if(able && CurPageUserAble.Able.indexOf(able) > -1){
                    this.tableData.btnGroup.splice(i,1);
                }
            }
        }

        this.tableData.columns.map(item => {
            switch (item.filterType) {
                case "text":
                    item.renderHeader = this.renderTextFilterWin;
                    break;
                case "dateTime":
                    item.renderHeader = this.renderDateTimeFiterWin;
                    break;
                case "selectTree":
                    item.renderHeader = this.renderSelectTreeFilterWin;
                    break;
                case "check":
                    item.filters = item.filterOptions;
                    item.filterRemote = function (val) {
                        let filterKey = item.filterKey ? item.filterKey : item.key;
                        self.query[filterKey] = val;
                        self.GetData(false);
                    };
                default:
                    break;
            }
        });
    },

    methods: {
        //根据值查找TreeSelect选中的title
        findSelectTreeLabel: function (value, treeObj) {
            let title = "";
            if (treeObj.value == value) {
                return treeObj.title;
            } else {
                if (treeObj.children && treeObj.children.length > 0) {
                    for (var i = 0; i < treeObj.children.length; i++) {
                        title = this.findSelectTreeLabel(value, treeObj.children[i]);
                        if (title != "") {
                            return title;
                        }
                    }
                    return "";
                } else {
                    return "";
                }
            }
        },
        getQuery: function () {
            var self = this;
            // this.query=this.$route.query;
            this.queryArray.splice(0, this.queryArray.length);
            var urlParams = AppFrame.Tools.UrlEvent.GetUrlParams(location.href);

            for (var i in urlParams) {
                if (i !== "Sort" && i !== "CurPage" && i !== "PageSize" && i !== "_t") {
                    let value = urlParams[i];
                    self.query[i] = value;
                    //alert(JSON.stringify(this.tableData.columns));
                    this.tableData.columns.map(function (item) {
                        if (item.key && (item.key === i || item.filterKey === i)) {
                            if (item.filterOptions && item.filterType == "check") {
                                let values = value.split(",");
                                let _val = [];
                                for (var j = 0; j < values.length; j++) {
                                    item.filterOptions.map(function (op) {
                                        if (values[j] == op.value + "") {
                                            _val.push(op.label);
                                        }
                                    });
                                }
                                value = _val.join(",");
                            }
                            if (item.filterOptions && item.filterType == "selectTree") {
                                let values = value.split(",");
                                let _val = [];
                                //console.log(JSON.stringify(item.filterOptions));
                                for (var j = 0; j < values.length; j++) {
                                    for (let i = 0; i < item.filterOptions.length; i++) {
                                        let title = self.findSelectTreeLabel(
                                            values[j],
                                            item.filterOptions[i]
                                        );
                                        if (title != "") {
                                            _val.push(title);
                                        }
                                    }
                                }
                                value = _val.join(",");
                            }
                            if (i != "" && value != "") {
                                self.queryArray.push({
                                    key: i,
                                    val: value,
                                    name: item.title
                                });
                            }
                        }
                    });
                }
            }
            //console.log(self.query);
        },
        onCloseFilter: function (item) {
            for (var i = this.queryArray.length - 1; i >= 0; i--) {
                if (this.queryArray[i].key == item.key) {
                    this.queryArray.splice(i, 1);
                }
            }
            delete this.query[item.key];

            this.GetData(false);
        },
        renderBaseFilterWindow: function (h, params, Content) {

            let self = this;
            let filterKey = params.column.filterKey ? params.column.filterKey : params.column.key;

            return h("span", [
                h("span", params.column.title),
                h(
                    "Poptip", {
                        props: {
                            placement: "bottom",
                            value: params.column._filterVisible,
                            transfer: true
                        },
                        on: {
                            "on-popper-show": function () {
                                params.column._filterVisible = true;
                            },
                            "on-popper-hide": function () {
                                params.column._filterVisible = false;
                            }
                        }
                    },
                    [
                        h(
                            "div", {
                                class: "ivu-poptip",
                                style: {
                                    marginLeft: "5px"
                                }
                            },
                            [
                                h("div",{
                                    class:'ivu-poptip-rel'
                                },[
                                    h("span",{
                                        class:'ivu-table-filter'
                                    },[
                                        h("i",{
                                            class:"ivu-icon ivu-icon-ios-funnel"
                                        })
                                    ])
                                ])

                            ]
                        ),

                        h(
                            "div", {
                                slot: "content",
                                style: {
                                    padding: "10px "
                                }
                            },
                            [
                                h("div", Content),
                                h(
                                    "div", {
                                        style: {
                                            marginTop: "10px",

                                            overflow: "hidden"
                                        }
                                    },
                                    [
                                        h(
                                            "Button", {
                                                props: {
                                                    size: "small",
                                                    type: "primary"
                                                },
                                                style: {
                                                    float: "right",
                                                    marginLeft: "5px"
                                                },
                                                on: {
                                                    click: function () {
                                                        // self.query[filterKey] = params.column.filterVal;
                                                        params.column._filterVisible = true;
                                                        setTimeout(function () {
                                                            params.column._filterVisible = false;
                                                        }, 100);
                                                        //  console.log(JSON.stringify(params.column));

                                                        if (self.query[filterKey] && self.query[filterKey] != "") {
                                                            self.GetData(false);
                                                        }

                                                    }
                                                }
                                            },
                                            "查询"
                                        ),
                                        h(
                                            "Button", {
                                                props: {
                                                    size: "small",
                                                    type: "dashed"
                                                },
                                                style: {
                                                    float: "right",
                                                    marginLeft: "5px"
                                                },
                                                on: {
                                                    click: function () {
                                                        delete self.query[filterKey];
                                                        params.column._filterVisible = true;
                                                        setTimeout(function () {
                                                            params.column._filterVisible = false;
                                                        }, 100);
                                                        self.GetData(false);
                                                    }
                                                }
                                            },
                                            "重置"
                                        )
                                    ]
                                )
                            ]
                        )
                    ]
                )
            ]);
        },

        renderTextFilterWin: function (h, params) {
            let self = this;
            let filterKey = params.column.filterKey ?
                params.column.filterKey :
                params.column.key;
            return this.renderBaseFilterWindow(h, params, [
                h("Input", {
                    props: {
                        size: "small",
                        placeholder: "请输入" + params.column.title,
                        value: self.query[filterKey]
                    },
                    style: {
                        width: "180px"
                    },
                    on: {
                        input: function (val) {
                            // params.column.filterVal = val;
                            self.query[filterKey] = val;
                        }
                    }
                })
            ]);
        },

        renderSelectTreeFilterWin: function (h, params) {
            // console.log(params.column.filterOptions);
            let self = this;
            let filterKey = params.column.filterKey ?
                params.column.filterKey :
                params.column.key;
            return this.renderBaseFilterWindow(h, params, [
                h("Tree", {
                    props: {
                        size: "small",
                        "show-checkbox": params.column.filterMultiple,
                        multiple: params.column.filterMultiple,
                        data: params.column.filterOptions
                    },
                    style: {
                        width: "180px"
                    },
                    on: {
                        "on-check-change": function (val) {
                            //console.log(val);
                            var ids = [];
                            val.forEach(function (item) {
                                ids.push(item.value);
                            });
                            self.query[filterKey] = ids.join(",");
                            //params.column._filterVisible=false;
                            setTimeout(function () {
                                params.column._filterVisible = true;
                            }, 0);
                        },
                        "on-select-change": function (selectItems) {
                            if (!params.column.filterMultiple) {
                                self.query[filterKey] = selectItems[0].value;
                            }
                            // console.log(self.query[filterKey]);
                            //params.column._filterVisible=false;
                            setTimeout(function () {
                                params.column._filterVisible = true;
                            }, 0);
                        },
                        "on-toggle-expand": function (val) {
                            //params.column._filterVisible = true;
                            //params.column._filterVisible=false;
                            setTimeout(function () {
                                params.column._filterVisible = true;
                            }, 0);
                        }
                    }
                })
            ]);
        },

        renderDateTimeFiterWin: function (h, params) {
            let self = this;
            let filterKey = params.column.filterKey ?
                params.column.filterKey :
                params.column.key;
            return h("span", [
                h("span", params.column.title),
                h(
                    "DatePicker", {
                        props: {
                            open: params.column._filterVisible,
                            value: self.query[filterKey],
                            confirm: true,
                            type: "daterange",
                            placement: "bottom-end",
                            transfer: true, //是否将弹层放置于 body 内
                            options: {
                                shortcuts: [{
                                        text: "最近一周",
                                        value() {
                                            const end = new Date();
                                            const start = new Date();
                                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                            return [start, end];
                                        }
                                    },
                                    {
                                        text: "最近一个月",
                                        value() {
                                            const end = new Date();
                                            const start = new Date();
                                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                            return [start, end];
                                        }
                                    },
                                    {
                                        text: "最近三个月",
                                        value() {
                                            const end = new Date();
                                            const start = new Date();
                                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                            return [start, end];
                                        }
                                    }
                                ]
                            }
                        },
                        on: {
                            "on-ok": function () {
                                params.column._filterVisible = false;
                                if (self.query[filterKey] && self.query[filterKey] != ",") {
                                    self.GetData(false);
                                }
                            },
                            "on-clear": function () {
                                delete self.query[filterKey];
                                params.column._filterVisible = false;
                                self.GetData(false);
                            },
                            "on-change": function (date) {
                                self.query[filterKey] = date;
                            }
                        }
                    },
                    [
                        h(
                            "div", {
                                class: "ivu-poptip",
                                attrs: {
                                    href: "javascript:void(0)"
                                },
                                style: {
                                    marginLeft: "5px"
                                },
                                on: {
                                    click: function () {
                                        params.column._filterVisible = !params.column._filterVisible;
                                    }
                                }
                            },
                            [
                                h("div",{
                                    class:'ivu-poptip-rel'
                                },[
                                    h("span",{
                                        class:'ivu-table-filter'
                                    },[
                                        h("i",{
                                            class:"ivu-icon ivu-icon-ios-funnel"
                                        })
                                    ])
                                ])

                            ]
                        )

                    ]
                )
            ]);
        },

        //选择行的时候
        onSelectionChange: function (selection) {
            let self = this;
            if (selection.length > 0) {
                let selectedRowKeys = [];
                self.btnGroupDisAbled = false;
                selection.forEach(function (item) {
                    selectedRowKeys.push(item[self.tableData.rowKey]);
                });
                self.selectedRowKeys = selectedRowKeys;
            } else {
                self.btnGroupDisAbled = true;
            }
            self.$emit("on-selection-change", selection);
        },

        //点击排序时
        onSortChange: function (data) {
            // alert(JSON.stringify(data));
            if (data.order === "normal") {
                delete this.query.Sort;
            } else {
                let SortKey = data.key;
                if (data.column.filterKey) {
                    SortKey = data.column.filterKey;
                }
                this.query.Sort = SortKey + "|" + data.order;
            }
            this.tableData.page.current = 1;
            this.GetData(true);
        },
        //选择分页尺寸时
        onPageSizeChange: function (pageSize) {
            this.tableData.page.pageSize = pageSize;
            if (this.tableData.page.current > 1) {
                this.tableData.page.current = 1;
            } else {
                this.$emit("on-page-change", {
                    current: 1,
                    pageSize: this.tableData.page.pageSize
                });
                this.GetData(true);
            }
        },
        //点击页码时
        onChange: function (page) {
            this.tableData.page.current = page;
            this.$emit("on-page-change", {
                current: this.tableData.page.current,
                pageSize: this.tableData.page.pageSize
            });
            this.GetData(true);
        },

        //构造Url并跳转
        GetData: function (IsSetHistroy) {
            var NewUrl = this.$route.path;
            NewUrl = AppFrame.Tools.UrlEvent.GetUrl(
                NewUrl,
                "CurPage",
                this.tableData.page.current
            );
            NewUrl = AppFrame.Tools.UrlEvent.GetUrl(
                NewUrl,
                "PageSize",
                this.tableData.page.pageSize
            );

            for (var name in this.query) {
                NewUrl = AppFrame.Tools.UrlEvent.GetUrl(NewUrl, name, this.query[name]);
            }

            if (IsSetHistroy) {
                this.$router.push(NewUrl);
            } else {
                this.$router.replace(NewUrl);
            }
        },

        onButtonClickEvent: function (btn) {
            var self = this;
            if (btn.actionText && btn.actionText != "") {
                self.$Modal.confirm({
                    title: "提示",
                    content: btn.actionText,
                    loading: true,
                    onOk: () => {
                        then(function (defer) {
                            doEvent(btn, defer);
                        }).fin(function (defer, err, ret) {
                            //console.log(err);
                            if (!ret || ret.Result == 0) {
                                self.$Message.error("操作错误,请重试");
                            }
                            self.$Modal.remove();
                            self.query["_t"] = moment().unix();
                            self.GetData(false);
                        });
                    }
                });
            } else {
                then(function (defer) {
                    doEvent(btn, defer);
                }).fin(function (defer, err, ret) {
                    if (!ret || ret.Result == 0) {
                        self.$Message.error("操作错误,请重试");
                    }
                    self.query["_t"] = moment().unix();
                    self.GetData(false);
                });
            }

            function doEvent(btn, cb) {
                //console.log(btn);
                AppFrame.Http.Post(btn.url, {
                        keys: self.selectedRowKeys
                    })
                    .then(function (Ret) {
                        if (cb) cb(null, Ret);
                    })
                    .catch(function (err) {
                        if (cb) cb(err);
                    });
            }
        }
    }
};
</script>

<style scoped>
</style>
